<template>
  <view class="my-posts-container">
    <view v-if="loading" class="loading">加载中...</view>
    <view v-else>
      <view v-if="posts.length === 0" class="empty">暂无发布的帖子</view>
      <view v-for="(post, index) in posts" :key="post.id" class="post-item">
        <view class="post-header">
          <image class="avatar" :src="avatarUrl" mode="aspectFill"></image>
          <view class="post-info">
            <text class="username">{{ userInfo.name }}</text>
            <text class="time">{{ post.created_at }}</text>
          </view>
        </view>
        <view class="post-content">
          <text class="post-text">{{ post.content }}</text>
          <view class="post-images" v-if="post.images && post.images.length">
            <image v-for="(img, imgIndex) in post.images" :key="imgIndex" :src="img" mode="aspectFill"></image>
          </view>
        </view>
        <view class="post-actions">
          <button class="edit-btn" @click="openEdit(post, index)">编辑</button>
          <button class="delete-btn" @click="confirmDelete(post, index)">删除</button>
        </view>
      </view>
      <!-- 编辑弹窗 -->
      <view v-if="showPopup" class="popup-mask" @click="closeEdit">
        <view class="edit-popup" @click.stop>
          <view class="edit-title">编辑帖子</view>
          <textarea v-model="editForm.content" maxlength="1000" class="edit-textarea" placeholder="请输入内容"></textarea>
          <view class="edit-images">
            <image v-for="(img, idx) in editForm.images" :key="idx" :src="img" mode="aspectFill" class="edit-img"></image>
            <button class="add-img-btn" v-if="editForm.images.length < 9" @click="chooseEditImage">添加图片</button>
          </view>
          <input v-model="editForm.location" class="edit-location" placeholder="请输入位置" />
          <view class="edit-actions">
            <button class="save-btn" @click="saveEdit">保存</button>
            <button class="cancel-btn" @click="closeEdit">取消</button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { request } from '@/utiles/request'

const posts = ref([])
const loading = ref(true)
const user_id = ref(null)
const userInfo = ref({})
const avatarUrl = 'https://img1.baidu.com/it/u=4113779165,197494311&fm=253&fmt=auto&app=120&f=JPEG?w=800&h=800'
const editForm = ref({
  id: null,
  content: '',
  images: [],
  location: ''
})
const editIndex = ref(null)
const showPopup = ref(false)

onMounted(() => {
  const local = uni.getStorageSync('userInfo');
  if (local && local.id) {
    user_id.value = local.id;
    userInfo.value = local;
  } else if (local && local.data && local.data.id) {
    user_id.value = local.data.id;
    userInfo.value = local.data;
  }
  loadMyPosts();
})

function openEdit(post, index) {
  editForm.value = {
    id: post.id,
    content: post.content,
    images: Array.isArray(post.images) ? [...post.images] : [],
    location: post.location || ''
  }
  editIndex.value = index
  showPopup.value = true
}

function closeEdit() {
  showPopup.value = false
}

async function loadMyPosts() {
  loading.value = true;
  try {
    const res = await request({
      url: '/admin/api/community/posts',
      method: 'GET',
      data: { user_id: user_id.value }
    });
    if (res.data.code === 200) {
      posts.value = res.data.data.list || [];
    } else {
      uni.showToast({ title: res.data.message || '加载失败', icon: 'none' });
    }
  } catch (e) {
    uni.showToast({ title: '网络错误', icon: 'none' });
  } finally {
    loading.value = false;
  }
}

async function saveEdit() {
  if (!editForm.value.content.trim()) {
    uni.showToast({ title: '内容不能为空', icon: 'none' });
    return;
  }
  try {
    const res = await request({
      url: `/admin/api/community/posts/${editForm.value.id}`,
      method: 'PUT',
      data: {
        user_id: user_id.value,
        content: editForm.value.content,
        images: editForm.value.images,
        location: editForm.value.location
      }
    });
    if (res.data.code === 200) {
      Object.assign(posts.value[editIndex.value], editForm.value);
      uni.showToast({ title: '保存成功', icon: 'success' });
      closeEdit();
    } else {
      uni.showToast({ title: res.data.message || '保存失败', icon: 'none' });
    }
  } catch (e) {
    uni.showToast({ title: '网络错误', icon: 'none' });
  }
}

function chooseEditImage() {
  uni.chooseImage({
    count: 9 - editForm.value.images.length,
    sizeType: ['original', 'compressed'],
    sourceType: ['album', 'camera'],
    success: async (res) => {
      editForm.value.images.push(...res.tempFilePaths);
    }
  });
}

function confirmDelete(post, index) {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这条帖子吗？',
    success: async (res) => {
      if (res.confirm) {
        await deletePost(post, index);
      }
    }
  });
}

async function deletePost(post, index) {
  try {
    const res = await request({
      url: `/admin/api/community/posts/${post.id}`,
      method: 'DELETE',
      data: { user_id: user_id.value }
    });
    if (res.data.code === 200) {
      posts.value.splice(index, 1);
      uni.showToast({ title: '删除成功', icon: 'success' });
    } else {
      uni.showToast({ title: res.data.message || '删除失败', icon: 'none' });
    }
  } catch (e) {
    uni.showToast({ title: '网络错误', icon: 'none' });
  }
}

function handleLogout() {
  uni.showModal({
    title: '提示',
    content: '确定要退出登录吗？',
    success: (res) => {
      if (res.confirm) {
        uni.clearStorageSync();
        uni.reLaunch({ url: '/pages/login/login' });
      }
    }
  });
}
</script>

<style>
.my-posts-container {
  min-height: 100vh;
  background: #f5f7fa;
  padding: 30rpx;
  position: relative;
}
.loading {
  text-align: center;
  color: #999;
  margin-top: 100rpx;
}
.empty {
  text-align: center;
  color: #999;
  margin-top: 100rpx;
}
.post-item {
  background: #fff;
  border-radius: 16rpx;
  margin-bottom: 30rpx;
  padding: 24rpx;
  box-shadow: 0 2rpx 12rpx rgba(0,0,0,0.05);
}
.post-header {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}
.avatar {
  width: 64rpx;
  height: 64rpx;
  border-radius: 50%;
  margin-right: 20rpx;
}
.post-info {
  flex: 1;
}
.username {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-right: 20rpx;
}
.time {
  font-size: 24rpx;
  color: #999;
  margin-top: 6rpx;
}
.post-content {
  margin-bottom: 20rpx;
}
.post-text {
  font-size: 28rpx;
  color: #333;
  line-height: 1.6;
}
.post-images {
  display: flex;
  flex-wrap: wrap;
  margin-top: 20rpx;
}
.post-images image {
  width: 180rpx;
  height: 180rpx;
  margin-right: 10rpx;
  margin-bottom: 10rpx;
  border-radius: 10rpx;
}
.post-actions {
  display: flex;
  justify-content: flex-end;
  gap: 20rpx;
}
.edit-btn {
  background: #1890ff;
  color: #fff;
  border: none;
  border-radius: 20rpx;
  padding: 0 30rpx;
  height: 56rpx;
  line-height: 56rpx;
  font-size: 26rpx;
}
.delete-btn {
  background: #ff4d4f;
  color: #fff;
  border: none;
  border-radius: 20rpx;
  padding: 0 30rpx;
  height: 56rpx;
  line-height: 56rpx;
  font-size: 26rpx;
}
.popup-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: center;
}
.edit-popup {
  background: #fff;
  border-radius: 20rpx;
  padding: 40rpx 30rpx;
  width: 90vw;
  max-width: 650rpx;
  box-shadow: 0 8rpx 32rpx rgba(0,0,0,0.18);
  position: relative;
  z-index: 1000;
}
.edit-title {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
  text-align: center;
}
.edit-textarea {
  width: 100%;
  height: 180rpx;
  font-size: 28rpx;
  padding: 16rpx;
  border: 1rpx solid #eee;
  border-radius: 8rpx;
  margin-bottom: 20rpx;
  box-sizing: border-box;
}
.edit-images {
  display: flex;
  flex-wrap: wrap;
  gap: 10rpx;
  margin-bottom: 20rpx;
}
.edit-img {
  width: 120rpx;
  height: 120rpx;
  border-radius: 8rpx;
}
.add-img-btn {
  background: #f5f7fa;
  color: #1890ff;
  border: 1rpx dashed #1890ff;
  border-radius: 8rpx;
  padding: 0 20rpx;
  height: 120rpx;
  line-height: 120rpx;
  font-size: 28rpx;
}
.edit-location {
  width: 100%;
  height: 60rpx;
  font-size: 28rpx;
  padding: 0 16rpx;
  border: 1rpx solid #eee;
  border-radius: 8rpx;
  margin-bottom: 20rpx;
  box-sizing: border-box;
}
.edit-actions {
  display: flex;
  justify-content: flex-end;
  gap: 20rpx;
}
.save-btn {
  background: #1890ff;
  color: #fff;
  border: none;
  border-radius: 20rpx;
  padding: 0 30rpx;
  height: 56rpx;
  line-height: 56rpx;
  font-size: 26rpx;
}
.cancel-btn {
  background: #ccc;
  color: #fff;
  border: none;
  border-radius: 20rpx;
  padding: 0 30rpx;
  height: 56rpx;
  line-height: 56rpx;
  font-size: 26rpx;
}
.logout-container {
  margin-top: 30rpx;
  padding-bottom: 30rpx;
}
.logout-btn {
  background-color: #FF6B6B;
  color: #fff;
  font-size: 32rpx;
  border-radius: 16rpx;
  width: 100%;
}
</style>